<template>
  <div>
    <!-- 上边 -->
    <el-card style="margin-top: 20px 0">
      <CategorySelect @getCategoryId="getCategoryId" :show="!isShowTable"></CategorySelect>
    </el-card>
    <!-- 下边 -->
    <el-card>
      <div v-show="isShowTable">
        <el-button type="primary" icon="el-icon-plus" :disabled="!category3Id" @click="addAttr">添加属性</el-button>
        <!-- 表格：展示平台属性 -->
        <el-table style="width: 100%" border :data="attrList">
          <el-table-column align="center" type="index" label="序号" width="80"> </el-table-column>
          <el-table-column prop="attrName" label="属性名称" width="150"> </el-table-column>
          <el-table-column prop="prop" label="属性值列表" width="width">
            <!-- 插槽 -->
            <template slot-scope="{ row, $index }">
              <el-tag type="success" v-for="(attrValue, index) in row.attrValueList" :key="attrValue.id" style="margin: 0 20px">
                {{ attrValue.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="180">
            <template slot-scope="{ row, $index }">
              <el-button type="warning" icon="el-icon-edit" size="mini" @click="updateAttr(row)">修改</el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- //添加属性和修改属性 -->
      <div v-show="!isShowTable">
        <!-- 行内表单 -->
        <el-form :inline="true" ref="form" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input placeholder="请输入属性名" v-model="attrInfo.attrName"></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" icon="el-icon-plus" @click="addAttrValue" :disabled="!attrInfo.attrName">添加属性值</el-button>
        <el-button @click="isShowTable = true">取消</el-button>
        <el-table style="width: 100%; margin: 20px 0" border :data="attrInfo.attrValueList">
          <el-table-column align="center" type="index" label="序号" width="80"> </el-table-column>
          <el-table-column label="属性值名称" width="width">
            <template slot-scope="{ row, $index }">
              <el-input
                placeholder="请输入属性名称"
                v-model="row.valueName"
                size="mini"
                v-if="row.flag"
                @blur="toLook(row)"
                @keyup.native.enter="toLook(row)"
                :ref="$index"
              ></el-input>
              <span v-else @click="toEdit(row, $index)" style="display: block">{{ row.valueName }}</span>
              <!-- span和input需要切换 -->
            </template>
          </el-table-column>
          <el-table-column label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-popconfirm :title="`确定删除${row.valueName}?`" @onConfirm="deleteAttrValue">
                <el-button type="danger" slot="reference" icon="el-icon-delete" size="mini"></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="addOrUpdateAttr" :disabled="attrInfo.attrValueList.length<1">保存</el-button>
        <el-button @click="isShowTable = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
//按需引入lodash当中的深拷贝
import cloneDeep from 'lodash/cloneDeep'
export default {
  name: 'Attr',
  data() {
    return {
      category1Id: '',
      category2Id: '',
      category3Id: '',
      attrList: [],
      isShowTable: true, //控制表格隐藏
      //收集和修改属性的使用
      attrInfo: {
        attrName: '', //属性名
        attrValueList: [], //属性值 因为有多个所以用数组
        categoryId: 0, //三级分类id
        categoryLevel: 3,
      },
    }
  },
  methods: {
    //自定义的回调
    getCategoryId({ categoryId, level }) {
      //区分几级id 以及父组件进行存储
      if (level == 1) {
        this.category1Id = categoryId
        this.category2Id = ''
        this.category3Id = ''
      } else if (level == 2) {
        this.category2Id = categoryId
        this.category3Id = ''
      } else {
        //三级id有了 展示数据要
        this.category3Id = categoryId
        //发起请求数据
        this.getAttrList()
      }
    },
    //获取平台属性的数据
    async getAttrList() {
      const { category1Id, category2Id, category3Id } = this
      let result = await this.$API.attr.reqAttrList(category1Id, category2Id, category3Id)
      if (result.code == 200) {
        console.log(result)
        this.attrList = result.data
      }
    },
    //添加属性值按钮的回调（按下按钮才出来input）
    addAttrValue() {
      console.log(122334)
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id, //属性名id
        valueName: '', //属性值名称
        flag: true, //切换input和sapn
      })
      this.$nextTick(() => {
        this.$refs[this.attrInfo.attrValueList.length - 1].focus()
      })
    },
    addAttr() {
      this.isShowTable = false
      //清除数据
      this.attrInfo = {
        attrName: '', //属性名
        attrValueList: [], //属性值 因为有多个所以用数组
        categoryId: this.category3Id, //三级分类id
        categoryLevel: 3,
      }
    },
    //修改某个属性
    updateAttr(row) {
      this.isShowTable = false
      console.log(row)
      // 点击修改将选择的属性给attrInfo
      this.attrInfo = cloneDeep(row) //数据对象里面有数组，数组里面还有对象，所以不能使用浅拷贝{...row},需要深拷贝！！！（可以使用插件loadlodash）
      this.attrInfo.attrValueList.forEach((item) => {
        this.$set(item, 'flag', false)
      })
    },
    toLook(row) {
      // console.log(row)
      console.log(6666)
      //判断数性值为空 不能作为属性值
      if (row.valueName.trim() == '') {
        this.$message('请输入正常属性值')
        return
      }
      // 新增属性值不能重复
      let isRepat = this.attrInfo.attrValueList.some((item) => {
        if (row != item) {
          return row.valueName == item.valueName
        }
      })
      console.log(isRepat)
      if (isRepat) return
      row.flag = false //切换input和sapn
    },
    toEdit(row, index) {
      row.flag = true
      // console.log(this.$refs[index]) //undefined 切换input和sapn 重排和重绘消耗时间
      this.$nextTick(() => {
        console.log(11111111)
        // console.log(this.$refs[index]) // 拿到input
        this.$refs[index].focus() //聚焦
      })
    },
    deleteAttrValue(index) {
      // console.log(111111111111111)
      this.attrInfo.attrValueList.splice(index, 1)
    },
    async addOrUpdateAttr() {
      // let result = await this.$API.attr.reqAddOrUpdateAttr()
      //整理参数 1.不为空  2.不包含flag
      //filter过滤
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter((item) => {
        //拿到不是空的

        if (item.valueName !== '') {
          delete item.flag
          return true
        }
      })
      try {
        await this.$API.attr.reqAddOrUpdateAttr(this.attrInfo)
        console.log(4646464)
        this.isShowTable = true
        this.$message({ type: 'success', message: '保存成功' })
        this.getAttrList() //保存成功 再次获得列表显示
      } catch (error) {
        this.isShowTable = true
        this.getAttrList() ///为了效果
      }
    },
  },
}
</script>

<style></style>
